<template>
    <div>
        <div style="margin-bottom: 5px;">
            <el-input v-model="name" placeholder="请输入商品名称" suffix-icon="el-icon-search" style="width: 200px;"
                @keyup.enter.native="loadPost"></el-input>
            <el-button type="primary" style="margin-left: 5px;" @click="loadPost">查询</el-button>
            <el-button type="success" @click="resetParam">重置</el-button>
<!--            <el-button type="primary" style="margin-left: 5px;" @click="add()">新增</el-button>-->
            <el-button type="primary" style="margin-left: 5px;" v-show="selectedRows.length !== 0" @click="generateOrder" >生成订单</el-button>
        </div>
        <el-table ref="table" :data="tableData" @selection-change="handleSelectionChange" :header-cell-style="{ background: '#f2f5fc', color: '#555555' }" border>
            <el-table-column type="selection" width="60" align="center"></el-table-column>
            <el-table-column prop="id" label="ID" width="80">
            </el-table-column>
            <el-table-column prop="picture" label="图片" width="150">
                <template slot-scope="scope"><img style="height: 80px" :src="scope.row.picture"></template>
            </el-table-column>
            <el-table-column prop="name" label="商品名称" width="200">
            </el-table-column>
            <el-table-column prop="price" label="价格" width="100">
            </el-table-column>
            <el-table-column prop="number" label="货号" width="100">
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="100">
            </el-table-column>
            <el-table-column prop="sale" label="销量" width="100">
            </el-table-column>
            <el-table-column prop="status" label="审核状态" width="100">
            </el-table-column>
            <el-table-column prop="operate" label="操作">
                <template slot-scope="scope">
                    <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
                    <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.id)" style="margin-left: 5px;">
                        <el-button slot="reference" size="small" type="danger">删除</el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
            :page-sizes="[5, 10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>

        <el-dialog title="提示" :visible.sync="centerDialogVisible" width="30%" center>
            <el-form ref="form" :rules="rules" :model="form" label-width="80px">
                <el-form-item label="图片" prop="picture">
                    <el-col :span="20">
                        <el-input v-model="form.picture"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="商品名称" prop="name" width="200px">
                    <el-col :span="20">
                        <el-input v-model="form.name"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-col :span="20">
                        <el-input v-model="form.price"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="货号" prop="number"  width="180px">
                    <el-col :span="20">
                        <el-input v-model="form.number"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-col :span="20">
                        <el-input v-model="form.sort"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="销量" prop="sale">
                    <el-col :span="20">
                        <el-input v-model="form.sale"></el-input>
                    </el-col>
                </el-form-item>
                <el-form-item label="审核状态" prop="status">
                    <el-col :span="20">
                        <el-input v-model="form.status"></el-input>
                    </el-col>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 抽屉组件 -->
        <el-drawer
            title="订单详情"
            :visible.sync="drawerVisible"
            direction="rtl"
            size="30%"
            @close="resetDrawer"
        >
          <div style="margin-left: 10px" v-if="selectedRows.length > 0">
            <div v-for="(item, index) in selectedRows" :key="index">
              <p>商品名称：{{ item.name }}</p>
              <p>价格：{{ item.price }}</p>
              <p><span style="margin-right: 10px">数量:</span><el-input-number v-model="item.quantity" :min="1" label="数量"></el-input-number></p>
            </div>
          </div>
          <div style="margin-top: 20px;margin-left: 10px">
            <el-button @click="drawerVisible = false">取消</el-button>
            <el-button type="primary" @click="submitOrder">提交订单</el-button>
          </div>
        </el-drawer>
    </div>
</template>

<script>
export default {
    name: "ProductList", // 更新组件名称
    data() {
        return {
            tableData: [],
            pageSize: 10,
            pageNum: 1,
            total: 0,
            name: '',
            centerDialogVisible: false,
            // showGenerateOrder: false,
            form: {
                id: '',
                picture: '', // 更新字段名称
                name: '',
                price: '',
                number: '',
                sort: '',
                sale: '',
                status: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' }
                ]
            },
            drawerVisible: false, // 控制抽屉的显示和隐藏
            selectedRows: [], // 新增属性，存储选中的行
            // 可以在这里添加一个属性来存储每个商品的数量，例如：
            quantities: {},
            now:'',
            user : JSON.parse(sessionStorage.getItem('CurUser')),
            lastId:0,
        }
    },
    methods: {
        resetForm() {
            this.$refs.form.resetFields();
        },
        del(id) {
            console.log(id)
            this.$axios.get(this.$httpUrl +'/productList/del?id='+id).then(res => res.data).then(res => { // 更新 API 端点
                  if (res.code === 200) {
                    this.$message({
                      message: '操作成功！',
                      type: 'success'
                    });
                    this.loadPost()
                  } else {
                    this.$message({
                      message: '操作失败！',
                      type: 'error'
                    })
                  }
            }
            )},
        mod(row) {
            this.centerDialogVisible = true
            this.$nextTick(() => {
                this.form.id = row.id
                this.form.picture = row.picture // 更新字段名称
                this.form.name = row.name
                this.form.price = row.price
                this.form.number = row.number
                this.form.sort = row.sort
                this.form.sale = row.sale
                this.form.status = row.status
            })
        },
        add() {
            this.centerDialogVisible = false
            // this.$nextTick(() => {
            //     this.resetForm()
            // })
            this.$router.push({ name: 'ProductAdd'});
        },
        doSave() {
            this.$axios.post(this.$httpUrl + '/productList/save', this.form).then(res => res.data).then(res => { // 更新 API 端点
                if (res.code == 200) {
                    this.$message({
                        message: '操作成功！',
                        type: 'success'
                    });
                    this.centerDialogVisible = false
                    this.loadPost()
                    this.resetForm()
                } else {
                    this.$message({
                        message: '操作失败！',
                        type: 'error'
                    });
                }
            })
        },
        doMod() {
            this.$axios.post(this.$httpUrl + '/productList/update', this.form).then(res => res.data).then(res => { // 更新 API 端点
                if (res.code == 200) {
                    this.$message({
                        message: '操作成功！',
                        type: 'success'
                    });
                    this.centerDialogVisible = false
                    this.loadPost()
                    this.resetForm()
                } else {
                    this.$message({
                        message: '操作失败！',
                        type: 'error'
                    });
                }
            })
        },
        save() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    if (this.form.id) {
                        this.doMod();
                    } else {
                        this.doSave();
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        handleSelectionChange(val) {
          this.selectedRows = val; // 更新选中的行
        },
        generateOrder() {
          console.log(this.selectedRows.length)
          // 这里是生成订单的逻辑
          console.log('生成订单', this.selectedRows);
          this.openDrawer()
          // 可以根据 selectedRows 来生成订单
          // this.$refs.table.clearSelection();
          // this.selectedRows = []
        },
        openDrawer() {
          this.drawerVisible = true;
          // 初始化数量选择框的值
          this.selectedRows.forEach(row => {
            this.quantities[row.id] = 1; // 默认数量为1
          });
        },
        resetDrawer() {
          // 重置数量选择框的值
          this.quantities = {};
        },
        generateOrderId() { //可不可以用状态管理
          if (this.$store.getters.getUserSelectedTime==null){
            this.now =  new Date();
          }else{
            this.now = this.$store.getters.getUserSelectedTime;
          }
          const now = this.now
          console.log(now)
          const year = this.getIncrease(now.getFullYear(), 4);
          const month = this.getIncrease(now.getMonth() + 1, 2);
          const day = this.getIncrease(now.getDate(), 2);
          const baseOrderId = `${year}${month}${day}01010`;
          return `${baseOrderId}${this.generateSequenceNumber()}`;
        },
        generateSequenceNumber() {
          // 从 localStorage 获取 lastId，如果不存在则默认为 0
          this.lastId = parseInt(localStorage.getItem('lastId')) || 0;
          // 返回填充了前导零的序列号
          return this.lastId.toString().padStart(5, '0');
        },
        getIncrease(num, digit) {
          var increase = "";
          for (var i = 0; i < digit; i++) {
            increase += "0";
          }
          return (increase + num).slice(-digit);
        },
        submitOrder() {
          // 构建符合后端 Order1 类型的订单数组
          const orders = this.selectedRows.map(row => {
            return {
              name:this.generateOrderId(),
              memberUsername:this.user.no,
              createTime:this.now,
              totalAmount: row.quantity * row.price,
              payType: 0, // 支付方式
            };
          });
          // 计算所有商品的总价
          const totalAmount = orders.reduce((sum, order) => sum + order.totalAmount, 0);
          // 如果后端接口需要总价，可以将其添加到订单数组的第一个元素或者单独作为一个订单发送
          if (orders.length > 0) {
            orders[0].totalAmount = totalAmount; // 将总价添加到第一个订单项
          }
          // 提交订单的逻辑
          console.log('提交订单', orders[0]);
          this.$axios.post(this.$httpUrl+'/order/save',orders[0]).then(res=>res.data).then(res=>{
            console.log(res)
            if(res.code==200){
              this.$message({
                message: '操作成功！',
                type: 'success'

              });
            }else{
              this.$message({
                message: '操作失败！',
                type: 'error'
              });
            }
          })
          // 关闭抽屉
          this.drawerVisible = false;
          // 清空选中行
          this.selectedRows = [];
          // 清除选择
          this.$refs.table.clearSelection();
          // 增加 lastId 并确保它是唯一的
          this.lastId += 1;
          // 将更新后的 lastId 存回 localStorage
          localStorage.setItem('lastId', this.lastId.toString());
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.pageNum = 1
            this.pageSize = val
            this.loadPost()
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.pageNum = val
            this.loadPost()
        },
        resetParam() {
            this.name = ''
        },
        loadPost() {
            this.$axios.post(this.$httpUrl + '/productList/listPage', { // 更新 API 端点
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                param: {
                    name: this.name
                }
            }).then(res => res.data).then(res => {
                if (res.code == 200) {
                    this.tableData = res.data
                    this.total = res.total
                } else {
                    alert('获取数据失败')
                }

            })
        }
    },
    beforeMount() {
        this.loadPost()
    }
}
</script>

<style scoped></style>